package com.zj.osm.view.project.projectdetail.fragment.scheme


import android.app.Activity
import android.app.AlertDialog
import android.app.ProgressDialog
import android.content.Intent
import android.graphics.Color
import android.os.Environment
import android.text.TextUtils
import android.view.View
import android.widget.*
import androidx.recyclerview.widget.GridLayoutManager
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.zj.osm.App
import com.zj.osm.R
import com.zj.osm.entity.db.PowerSupplySchemeDetailsDao
import com.zj.osm.entity.greendao.PowerSupplyScheme
import com.zj.osm.entity.greendao.PowerSupplySchemeDetails
import com.zj.osm.entity.greendao.Project
import com.zj.osm.mvp.MvpFragment
import com.zj.osm.utils.ThreadManager
import com.zj.osm.utils.WordUtils
import com.zj.osm.view.project.projectdetail.ProjectDetailActivity.PROJECT_DETAILS_ID
import com.zj.osm.view.project.projectdetail.fragment.BasisFragment
import com.zj.utils.utils.ShareUtils
import com.zj.utils.utils.SpinnerUtils.setSpinnerItemSelectedByValue
import com.zj.utils.utils.utilcode.ToastUtils
import com.zj.utils.view.image.ImageBean
import com.zj.utils.view.image.ReleaseSchemeAdapter
import kotlinx.android.synthetic.main.fragment_power_supply_scheme.*
import kotlinx.android.synthetic.main.fragment_scheme_scheme.*
import kotlinx.android.synthetic.main.layout_details.*
import java.io.File
import java.io.IOException
import java.util.*

/**
 * 供电方案
 */
class PowerSupplySchemeFragment : MvpFragment<PowerSupplySchemeView, PowerSupplySchemePresenter>(), View.OnClickListener, ReleaseSchemeAdapter.OnDeleteItemListener, PowerSupplySchemeView {

    private var powerSupplyScheme = PowerSupplyScheme()
    private var whetherToModify = false //是否可以修改
    private var adapter: ReleaseSchemeAdapter? = null //附加图片适配器
    private val imageBeanList = ArrayList<ImageBean>() //附加图片集合
    private val daoSession = App.getInstances().daoSession
    private var project = Project()

    override fun createPresenter(): PowerSupplySchemePresenter {
        return PowerSupplySchemePresenter()
    }

    override fun createView(): PowerSupplySchemeView {
        return this
    }

    override fun getContentViewLayoutID(): Int {
        return R.layout.fragment_power_supply_scheme
    }

    override fun onStart() {
        super.onStart()
        presenter.initData(PROJECT_DETAILS_ID)
    }

    override fun onResume() {
        super.onResume()
        initView()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        if (detailsTvOne.text == "修改") {
            whetherToModify = true
            setUpdate(whetherToModify)
            detailsTvOne.text = "保存"
        } else {
            detailsTvOne.text = "修改"
            whetherToModify = false
            setUpdate(whetherToModify)
            save()
        }
    }

    /**
     * 初始化数据 获取项目和供电方案
     */
    override fun initData(project: Project, powerSupplyScheme: PowerSupplyScheme, powerSupplySchemeDetailsList: MutableList<PowerSupplySchemeDetails>) {
        this.project = project
        this.powerSupplyScheme = powerSupplyScheme
        viewInterface()
        initPowerSupplyScheme(powerSupplySchemeDetailsList)
    }

    /**
     * 初始化电源信息
     */
    private fun initPowerSupplyScheme(supplySchemeDetails: MutableList<PowerSupplySchemeDetails>) {
        val schemeLl = activity!!.window!!.decorView.findViewById<LinearLayout>(R.id.schemeLl)
        schemeLl.removeAllViews()
        if (supplySchemeDetails.size > 0) {
            for (i in supplySchemeDetails.indices) {
                val views = View.inflate(context, R.layout.fragment_scheme_scheme, null)
                val schemeTvSourceCode = views.findViewById<TextView>(R.id.schemeTvSourceCode)//电源编号
                val schemeTvSourceType = views.findViewById<TextView>(R.id.schemeTvSourceType)//电源类型
                val schemeTvVoltageLevel = views.findViewById<TextView>(R.id.schemeTvVoltageLevel)//电压等级
                val schemeTvLineNumber = views.findViewById<TextView>(R.id.schemeTvLineNumber)//线(站)号
                val schemeTvRunMethod = views.findViewById<TextView>(R.id.schemeTvRunMethod)//运行方式
                val schemeTvPowerSupplyCapacity = views.findViewById<TextView>(R.id.schemeTvPowerSupplyCapacity)//供电容量
                val schemeTvImportLineMethod = views.findViewById<TextView>(R.id.schemeTvImportLineMethod)//进线方式
                val schemeTvUpdate = views.findViewById<TextView>(R.id.schemeTvUpdate)//修改
                if (whetherToModify) {
                    schemeTvUpdate.visibility = View.VISIBLE
                } else {
                    schemeTvUpdate?.visibility = View.GONE
                }
                schemeTvSourceCode.text = supplySchemeDetails[i].sourceCode
                schemeTvSourceType.text = supplySchemeDetails[i].sourceType
                schemeTvVoltageLevel.text = supplySchemeDetails[i].voltageLevel
                schemeTvLineNumber.text = supplySchemeDetails[i].lineNumber
                schemeTvRunMethod.text = supplySchemeDetails[i].runMethod
                schemeTvPowerSupplyCapacity.text = supplySchemeDetails[i].powerSupplyCapacity
                schemeTvImportLineMethod.text = supplySchemeDetails[i].importLineMethod
                schemeLl.addView(views)
                schemeTvUpdate?.setOnClickListener { addScheme(supplySchemeDetails[i]) }
            }
        }
    }

    override fun OnDeleteItem(position: Int) {
        imageBeanList.removeAt(position)
        adapter?.notifyDataSetChanged()
    }


    /**
     * 处理返回结果。
     *
     * @param requestCode 请求码
     * @param resultCode  结果码 成功 -1 失败 0
     * @param data        返回的数据
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                val paths = PictureSelector.obtainMultipleResult(data)
                for (i in paths.indices) {
                    imageBeanList.add(ImageBean(paths[i].cutPath, paths[i].path))
                }
                adapter?.notifyDataSetChanged()
            }
        }
    }


    /**
     * 初始化显示界面数据
     */
    private fun viewInterface() {
        adapter = ReleaseSchemeAdapter(this, imageBeanList)
        schemeRecyclerView.adapter = adapter
        val gridLayoutManager = GridLayoutManager(context, 4)
        schemeRecyclerView.layoutManager = gridLayoutManager
        adapter?.setOnDeleteItemListener(this)
        if (!TextUtils.isEmpty(powerSupplyScheme.applyCode)) //申请编号
            schemeEdApplyCode.setText(powerSupplyScheme.applyCode)
        if (!TextUtils.isEmpty(powerSupplyScheme.applyType)) //申请类型
            schemeEdApplyType.setText(powerSupplyScheme.applyType)
        if (!TextUtils.isEmpty(powerSupplyScheme.projectName)) //项目名称
            schemeEdProjectName.setText(powerSupplyScheme.projectName)
        if (!TextUtils.isEmpty(powerSupplyScheme.userCode)) //用户编号
            schemeEdUserCode.setText(powerSupplyScheme.userCode)
        if (!TextUtils.isEmpty(powerSupplyScheme.userName)) //用户名称
            schemeEdUserName.setText(powerSupplyScheme.userName)
        if (!TextUtils.isEmpty(powerSupplyScheme.address)) //联系地址
            schemeEdAddress.setText(powerSupplyScheme.address)
        if (!TextUtils.isEmpty(powerSupplyScheme.electricityAddress)) //用电地址
            schemeEdElectricityAddress.setText(powerSupplyScheme.electricityAddress)
        if (!TextUtils.isEmpty(powerSupplyScheme.operator)) //经办人
            schemeEdOperator.setText(powerSupplyScheme.operator)
        if (!TextUtils.isEmpty(powerSupplyScheme.operatorPortableTelephone)) //经办人电话
            schemeEdOperatorPhone.setText(powerSupplyScheme.operatorPortableTelephone)
        if (!TextUtils.isEmpty(powerSupplyScheme.pic)) //负责人
            schemeEdPic.setText(powerSupplyScheme.pic)
        if (!TextUtils.isEmpty(powerSupplyScheme.picPortableTelephone)) //负责人电话
            schemeEdPicPhone.setText(powerSupplyScheme.picPortableTelephone)
        if (!TextUtils.isEmpty(powerSupplyScheme.schemeExplain)) //供电方式说明
            schemeEdSchemeExplain.setText(powerSupplyScheme.schemeExplain)
        if (!TextUtils.isEmpty(powerSupplyScheme.diagram)) { //供电方式说明
            imageBeanList.add(ImageBean(powerSupplyScheme.diagram, powerSupplyScheme.diagram))
            adapter?.notifyDataSetChanged()
        }
    }

    /**
     * 是否处于修改状态
     * true 为可以修改
     * false 为不可修改
     */
    private fun setUpdate(isUpdate: Boolean) {
        schemeEdApplyCode.isEnabled = isUpdate
        schemeEdApplyType.isEnabled = isUpdate
        schemeEdProjectName.isEnabled = isUpdate
        schemeEdUserCode.isEnabled = isUpdate
        schemeEdUserName.isEnabled = isUpdate
        schemeEdAddress.isEnabled = isUpdate
        schemeEdElectricityAddress.isEnabled = isUpdate
        schemeEdOperator.isEnabled = isUpdate
        schemeEdOperatorPhone.isEnabled = isUpdate
        schemeEdPic.isEnabled = isUpdate
        schemeEdPicPhone.isEnabled = isUpdate
        schemeEdSchemeExplain.isEnabled = isUpdate
        if (isUpdate) {
            schemeTvUpdate?.visibility = View.VISIBLE
            schemeLlFujia.visibility = View.VISIBLE
            schemeBtnAdd.visibility = View.VISIBLE
        } else {
            schemeTvUpdate?.visibility = View.GONE
            schemeLlFujia.visibility = View.GONE
            schemeBtnAdd.visibility = View.GONE
        }
    }

    /**
     * 初始化页面
     */
    private fun initView() {
        detailsBtnJc.setBackgroundResource(R.drawable.btn_shape_white)
        detailsBtnKcxx.setBackgroundResource(R.drawable.btn_shape_white)
        detailsBtnWlqd.setBackgroundResource(R.drawable.btn_shape_white)
        detailsBtnGdfa.setBackgroundResource(R.drawable.btn_shape)
        detailsBtnJc.setTextColor(Color.rgb(51, 51, 51))
        detailsBtnKcxx.setTextColor(Color.rgb(51, 51, 51))
        detailsBtnWlqd.setTextColor(Color.rgb(51, 51, 51))
        detailsBtnGdfa.setTextColor(Color.rgb(255, 255, 255))
        BasisFragment().clickItem(this, detailsBtnBack, detailsBtnJc, detailsBtnKcxx, detailsBtnWlqd, detailsBtnGdfa)
    }

    override fun initListener() {
        schemeBtnAdd.setOnClickListener(this)
        detailsBtnJc.setOnClickListener(this)
        detailsBtnKcxx.setOnClickListener(this)
        detailsBtnWlqd.setOnClickListener(this)
        detailsBtnGdfa.setOnClickListener(this)
        detailsTvTwo.text = "导出"
        detailsTvOne.text = "修改"
        detailsTvOne.setOnClickListener(this)
        detailsTvTwo.setOnClickListener(this)
        setUpdate(whetherToModify)
    }

    override fun onClick(v: View?) {
        if (v != null) {
            when (v.id) {
                R.id.schemeBtnAdd -> {//添加电源信息
                    addScheme(null)
                }
                R.id.detailsTvOne -> {//保存
                    if (detailsTvOne.text == "修改") {
                        whetherToModify = true
                        setUpdate(whetherToModify)
                        detailsTvOne.text = "保存"
                    } else {
                        detailsTvOne.text = "修改"
                        whetherToModify = false
                        setUpdate(whetherToModify)
                        save()
                    }
                }
                R.id.detailsTvTwo -> {//导出
                    exportSure()
                }
            }
        }
    }

    /**
     * 保存当前配置
     */
    private fun save() {
        var imagePath = ""
        if (imageBeanList.size > 0)
            imagePath = imageBeanList[0].path
        daoSession.powerSupplySchemeDao.update(PowerSupplyScheme(
                powerSupplyScheme.id,
                schemeEdApplyCode.text.toString(), //申请编号
                schemeEdUserCode.text.toString(), //用户编号
                schemeEdUserName.text.toString(), //用户名称
                schemeEdProjectName.text.toString(), //项目名称
                schemeEdElectricityAddress.text.toString(),
                schemeEdApplyType.text.toString(),
                schemeEdAddress.text.toString(),
                schemeEdOperator.text.toString(),
                "", schemeEdOperatorPhone.text.toString(),
                schemeEdPic.text.toString(),
                "", schemeEdPicPhone.text.toString(),
                schemeEdSchemeExplain.text.toString(),
                "同意", Date().time.toString(),
                imagePath, "", project.id
        ))
        ToastUtils.showShort("保存成功")
    }


    /**
     * 添加电源信息
     */
    private fun addScheme(powerSupplySchemeDetails: PowerSupplySchemeDetails?) {
        val views = View.inflate(context, R.layout.fragment_scheme_dialog, null)
        val schemeEdSourceCode = views.findViewById<EditText>(R.id.schemeEdSourceCode)//电源编号
        val schemeSpSourceType = views.findViewById<Spinner>(R.id.schemeSpSourceType)//电源类型
        val schemeSpVoltageLevel = views.findViewById<Spinner>(R.id.schemeSpVoltageLevel)//电压等级
        val schemeEdLineNumber = views.findViewById<EditText>(R.id.schemeEdLineNumber)//线(站)号
        val schemeEdRunMethod = views.findViewById<EditText>(R.id.schemeEdRunMethod)//运行方式
        val schemeEdPowerSupplyCapacity = views.findViewById<EditText>(R.id.schemeEdPowerSupplyCapacity)        //供电容量
        val schemeEdImportLineMethod = views.findViewById<EditText>(R.id.schemeEdImportLineMethod)//进线方式
        val schemeBtnDelete = views.findViewById<Button>(R.id.schemeBtnDelete) //删除按钮
        val schemeBtnCancel = views.findViewById<Button>(R.id.schemeBtnCancel) //取消按钮
        val schemeBtnConfirm = views.findViewById<Button>(R.id.schemeBtnConfirm) //确认按钮

        //传进来不为空则为修改
        if (powerSupplySchemeDetails != null) {
            schemeEdSourceCode.setText(powerSupplySchemeDetails.sourceCode)
            setSpinnerItemSelectedByValue(schemeSpSourceType, powerSupplySchemeDetails.sourceType)
            setSpinnerItemSelectedByValue(schemeSpVoltageLevel, powerSupplySchemeDetails.voltageLevel)
            schemeEdLineNumber.setText(powerSupplySchemeDetails.lineNumber)
            schemeEdRunMethod.setText(powerSupplySchemeDetails.runMethod)
            schemeEdPowerSupplyCapacity.setText(powerSupplySchemeDetails.powerSupplyCapacity)
            schemeEdImportLineMethod.setText(powerSupplySchemeDetails.importLineMethod)
            schemeBtnDelete.visibility = View.VISIBLE
        }

        //显示添加电源信息模态弹窗
        val dialog = AlertDialog.Builder(context).create()
        dialog.setView(views)
        dialog.show()
        schemeBtnDelete.setOnClickListener {
            dialog.dismiss()
            daoSession.powerSupplySchemeDetailsDao.deleteByKey(powerSupplySchemeDetails?.id)
            refreshSchemeDetails()
            ToastUtils.showShort("删除成功")
        }
        schemeBtnCancel.setOnClickListener {
            dialog.dismiss()
        }
        schemeBtnConfirm.setOnClickListener {
            if (schemeEdSourceCode.text.toString() == ""
                    || schemeEdLineNumber.text.toString() == ""
                    || schemeEdRunMethod.text.toString() == ""
                    || schemeEdPowerSupplyCapacity.text.toString() == ""
                    || schemeEdImportLineMethod.text.toString() == "") {
                ToastUtils.showShort("请输入完整信息")
            } else {
                dialog.dismiss()
                if (powerSupplySchemeDetails != null) {//如果传进来有值修改，为null新增
                    daoSession.powerSupplySchemeDetailsDao.update(PowerSupplySchemeDetails(powerSupplySchemeDetails.id, schemeEdSourceCode.text.toString(),
                            schemeSpSourceType.selectedItem.toString(),
                            schemeSpVoltageLevel.selectedItem.toString(),
                            schemeEdLineNumber.text.toString(),
                            schemeEdRunMethod.text.toString(),
                            schemeEdPowerSupplyCapacity.text.toString(),
                            schemeEdImportLineMethod.text.toString(),
                            powerSupplyScheme.id))
                } else {
                    daoSession.powerSupplySchemeDetailsDao.insert(PowerSupplySchemeDetails(null, schemeEdSourceCode.text.toString(),
                            schemeSpSourceType.selectedItem.toString(),
                            schemeSpVoltageLevel.selectedItem.toString(),
                            schemeEdLineNumber.text.toString(),
                            schemeEdRunMethod.text.toString(),
                            schemeEdPowerSupplyCapacity.text.toString(),
                            schemeEdImportLineMethod.text.toString(),
                            powerSupplyScheme.id))
                }
                refreshSchemeDetails()
                ToastUtils.showShort("保存成功")
            }

        }

    }

    private fun refreshSchemeDetails() {
        initPowerSupplyScheme(daoSession.powerSupplySchemeDetailsDao.queryBuilder().where(PowerSupplySchemeDetailsDao.Properties.PowerSupplySchemeId.eq(powerSupplyScheme.id)).list())
    }

    /**
     * 创建ProgressDialog
     */
    private fun createProgressDialog() {
        mProgressDialog = ProgressDialog(context)
        mProgressDialog?.setMessage("正在导出文件，请稍后。。。")
        mProgressDialog?.show()
        mProgressDialog?.setCanceledOnTouchOutside(false)
    }

    private var mProgressDialog: ProgressDialog? = null

    /**
     * 是否确定导出对话框
     */
    private fun exportSure() {
        val normalDialog = AlertDialog.Builder(context)
        normalDialog.setTitle("导出word")
        normalDialog.setMessage("是否导出word文件??")
        normalDialog.setPositiveButton("确定"
        ) { dialog, _ ->
            try {
                dialog.dismiss()
                createProgressDialog()//显示转圈对话框
                val threadPool = ThreadManager.getThreadPool()//线程池
                threadPool.execute {
                    presenter.exportWord(project.id)
                    activity!!.runOnUiThread {
                        if (mProgressDialog != null) {
                            mProgressDialog?.cancel()
                        }
                    }
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        normalDialog.setNegativeButton("取消"
        ) { dialog, _ -> dialog.dismiss() }
        //显示
        normalDialog.show()
    }

    /**
     * 导出Word文档回调
     */
    override fun exportWord(map: HashMap<String, Any>, powerSupplyScheme: PowerSupplyScheme, powerSupplySchemeDetailsList: MutableList<PowerSupplySchemeDetails>) {
        //从assets读取我们的Word模板
        val `is` = activity!!.assets.open("scheme.docx")
        //创建生成的文件
        val newFile = File(Environment.getExternalStorageDirectory().absolutePath
                + "/bhne/" + project.name + "/" + project.name + ".docx")
        WordUtils().writeDoc(`is`, newFile, map, powerSupplyScheme, powerSupplySchemeDetailsList)
        ShareUtils.shareFile(context, newFile)
    }


}
